﻿using Company.Application.Data.Interfaces;
using Company.Database.Entities;
using Company.Database.Interfaces;
using Company.Demo.Models;
using Company.Demo.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TookKit.Mvvm.Attributes;
using TookKit.Mvvm.Bindings;
using TookKit.Mvvm.Enums;
using TookKit.Mvvm.Events;

namespace Company.Demo.ViewModels
{
    [DependencyInjection(Lifetime.Singleton)]
    internal class ShellViewModel : ObservableObject
    {
        public ICommand LoadedCommand { get; }
        private string title = "IOC框架开发实战课程";
        public string Title
        {
            get { return title; }
            //set { title = value; OnPropertyChanged(); }

            set { SetProperty(ref title, value); }
        }

        private ContentControl container = null;
        public ShellViewModel(
            LoginView loginView,
            MainView mainView,
            IUserRepository userRepository)
        {            

            //LoadedCommand = new RelayCommand(Loaded);

            //LoadedCommand = new RelayCommand(Loaded, CanExecute);

            LoadedCommand = new RelayCommand<ContentControl>(view =>
            {
                container = view;

                container.Content = loginView;
            });


            //首次启动系统，创建管理员账户
            var user = userRepository.GetAll().FirstOrDefault();
            if (user == null)
            {
                User newUser = new User();
                newUser.UserName = "admin";
                newUser.Password = "12345678";
                newUser.InsertDate=DateTime.Now;
                int count = userRepository.Insert(newUser);
                if(count > 0) 
                {
                    MessageBox.Show("首次启动系统，创建管理员账户\r\n用户:admin\r\n密码:12345678");
                }
            }

            //订阅登录成功事件
            EventBus.Default.Subscribe<LoginMessage>((sender, message) =>
            {
                MessageBox.Show($"登录成功\r\nsender:{sender}\r\nmessage:{message}");

                //切换到主界面
                container.Content = mainView;
            });

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(2500);
                Title = "讲师:重庆教主";
            });
        }

        private bool CanExecute()
        {
            if (DateTime.Now.Second % 2 == 0)
            {
                return true;
            }
            return false;
        }

        private void Loaded()
        {
            MessageBox.Show($"Loaded Time:{DateTime.Now}");
        }
    }
}
